package com.skyon.rule.res.spring;

/**
 * 实现Spring的加载接口，并实现加载共用的操作
 * @author cfans
 */
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;

public abstract class AbstractPlotSessionBeanFactory implements FactoryBean<LocalSessionFactory>, InitializingBean, DisposableBean {

	
	protected final Log logger = LogFactory.getLog(getClass());

	private LocalSessionFactory sessionFactory;
	
	
	public void afterPropertiesSet() throws Exception {
		LocalSessionFactory rawSf = buildSessionFactory();
		this.sessionFactory = wrapSessionFactoryIfNecessary(rawSf);
		afterSessionFactoryCreation();
	}
	
	@Override
	public void destroy() throws Exception {
		logger.info("Closing PlotServer SessionFactory");
		try {
			beforeSessionFactoryDestruction();
		}
		finally {
		}
	}
	

	protected abstract LocalSessionFactory buildSessionFactory() throws Exception;
	

	protected final LocalSessionFactory getSessionFactory() {
		if (this.sessionFactory == null) {
			throw new IllegalStateException("SessionFactory not initialized yet");
		}
		return this.sessionFactory;
	}

	public LocalSessionFactory getObject() throws Exception {
		return this.sessionFactory;
	}

	public Class<?> getObjectType() {
		return (this.sessionFactory != null ? this.sessionFactory.getClass() : LocalSessionFactory.class);
	}

	public boolean isSingleton() {
		return true;
	}
	
	protected void beforeSessionFactoryDestruction() {
		
	}
	
	protected void afterSessionFactoryCreation() {
	}

	protected LocalSessionFactory wrapSessionFactoryIfNecessary(LocalSessionFactory rawSf) {
		return rawSf;
	}

}
